$(function () {
    // 添加明细
    $(".appendRow").click(function () {
        // 1. 获取到表格中的第一行,并克隆
        var tr = $("#edit_table_body tr:first").clone();
        // 2. 清空行中的数据
        tr.find("[tag=product]").val("");
        tr.find("[tag=saleprice]").val("");
        tr.find("[tag=srotName]").val("");
        tr.find("[tag=saleCount]").val("");
        tr.find("[tag=AmountPrice]").val("");
        /*tr.find("[tag=brand]").text("");
         tr.find("[tag=amount]").text("");*/
        // 3. 追加到表格中
        tr.appendTo("#edit_table_body");
    });
    // 更新多条明细名称提交时的索引值
    $("#sale_sbumit").submit(function () {
        // 1. 获取tbody中的所有行
        var trArray = $("#edit_table_body tr");
        for (var i = 0; i < trArray.size(); i++) {
            var tr = $(trArray[i]);
            // 修改需要提交的表单的名称,加上新的索引值
            tr.find("[tag=pid]").prop("name", "items[" + i + "].product.id");
            tr.find("[tag=costPrice]").prop("name", "items[" + i + "].costPrice");
            tr.find("[tag=number]").prop("name", "items[" + i + "].number");
            tr.find("[tag=remark]").prop("name", "items[" + i + "].remark");
        }
    });
    //计算小计


    $("#edit_table_body").on("click", "[tag=saleprice],[tag=saleCount],[tag=sn]", function () {
        var tr = $(this).closest("tr");

        var saleprice = parseFloat(tr.find("[tag=saleprice]").val() || 0);
        var number = parseFloat(tr.find("[tag=saleCount]").val() || 0);

        var amount = number * saleprice;
        // 3. 将结果保留两位小数,四舍五入
        // 4. 将计算后的结果设置到页面
        tr.find("[tag=SaleAmount]").text(amount.toFixed(2));

        // 删除明细
    }).on("click", ".removeItem", function () {
        var tr = $(this).closest("tr");
        // 1. 获取所有的tr,判断tr数组是否大于1
        if ($("#edit_table_body tr").size() > 1) {
            // 2. 如果数量大于1,直接删除当前行
            tr.remove();
        } else {
            // 3. 否则清空当前行的数据
            tr.find("[tag=pid]").val("");
            tr.find("[tag=name]").val("");
            tr.find("[tag=costPrice]").val("");
            tr.find("[tag=number]").val("");
            tr.find("[tag=remark]").val("");
            tr.find("[tag=brand]").text("");
            tr.find("[tag=amount]").text("");
        }
    });
    $('#tb').textbox({
        buttonText: 'Search',
    });

    //商品新息表
    $("#order_product").datagrid({
        fit: true,
        url: "/product/list",
        fitColumns: true,
        /*data: [
         {productSn:'1', productName:'360儿童手表',integral:'200',classify_one:'手表',classify_two:'儿童手表',salePrice:'200'},
         {productSn:'2', productName:'锤子坚果手机',integral:'2000',classify_one:'手机',classify_two:'塞班手机',salePrice:'2500'}
         //{id:'1', productName:'锤子坚果手机',productSrotName:'手机',salePrice:'2000',saleCount:'1',AmountPrice:'2000'},
         //{id:'2', productName:'锤子坚果手机',integral:'2000',firstClassify:'手机',secondClassify:'塞班手机',salePrice:'2500'},

         ],*/
        columns: [[
            {field: 'sn', title: '编号', width: 100},
            {field: 'name', title: '商品', width: 100},
            {field: 'point', title: '积分', width: 100},
            {
                field: 'parentClassify', title: '一级分类', width: 100, formatter: function (value) {
                return value ? value.name : "";
            }
            },
            {
                field: 'productClassify', title: '二级分类', width: 100, formatter: function (value) {
                return value ? value.name : "";
            }
            },
            {field: 'salePrice', title: '售价', width: 100}
        ]],
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        toolbar: '#tb_product',
        sortName: 'hireDate',
        onClickRow: function (index, row) {
            /*  服务人员*/
            $("#saleName").val("admin");
            /* 业务时间*/
            $("#dataTime").val(new Date(), pattern = "yyyy-MM-dd");
            /* 流水单号*/
            ;
            $("#saleOrderNumber").val((Math.random() * 100000 + "").substring(1, 6));
            var tr = $("#edit_table_body tr:last");
            for (var i = 0; i < tr.size(); i++) {
                /*  商品名称*/
                $($(tr[i]).find("[tag=product]")).val(row.name)
                //$("tr [tag=product]").val(row.productName);
                /*单价*/
                $($(tr[i]).find("[tag=saleprice]")).val(row.salePrice);
                //$("tr [tag=saleprice]").val(row.salePrice);
                /*品牌*/
                $($(tr[i]).find("[tag=srotName]")).val(row.productClassify.name);
                //$("tr [tag=srotName]").val(row.productSort_two.name);
                /*数量*/
                $($(tr[i]).find("[tag=saleCount]")).val(1);
                //$("tr [tag=saleCount]").val(1);
                /* 总价*/
                $($(tr[i]).find("[tag=AmountPrice]")).val($("[tag=saleprice]").val() * $("[ tag=saleCount]").val());
                //$("tr [tag=AmountPrice]").val($("[tag=saleprice]").val() * $("[ tag=saleCount]").val())
            }
        }
    })
    //会员信息表
    $("#emp_datagrid").datagrid({
        fit: true,
        url: "/member/list",
        /* data: [
         {memberName:'朱先生', memberNumber:'1101',grade:'高级会员',balance:'30000',integral:'20000',discount:'0.8'},
         {memberName:'李小姐', memberNumber:'1102',grade:'钻石会员',balance:'100000',integral:'50000',discount:'0.5'}
         ],*/
        fitColumns: true,
        columns: [[
            {field: 'memberName', title: '姓名', width: 100},
            {field: 'memberNumber', title: '卡号', width: 100},
            {
                field: 'grade', title: '等级', width: 100, formatter: function (value) {
                console.log(value.sn);
                return value ? value.name : "";
            }
            },
            {field: 'balance', title: '余额', width: 100},
            {field: 'integral', title: '积分', width: 100},
            {
                field: 'sn', title: '折扣', width: 100, formatter: function (value, row, index) {
                return row.grade.sn ? row.grade.sn : "";
            }
            }





        ]],
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        toolbar: '#tb_member',
        sortName: 'hireDate',
        onClickRow: function (index, row) {
            $("#memberNumber").val(row.memberNumber);
            $("#memberdiscount").val(row.grade.sn);
            $("#memberbalance").val(row.balance);
            $("#memberId").prop('value',row.id);
        }
    });
    //结算
    var salePrice;
    var amount;
    $("#btn_close").click(function () {
        var trArray = $("#edit_table_body tr");
        var amount = 0;
        for (var i = 0; i < trArray.size(); i++) {
            var tr = $(trArray[i]);
            salePrice = tr.find("[tag=saleprice]").val();

            discount = $("#memberdiscount").val();

            var saleCount = tr.find("#saleCount").val();

            //小计
            amount = discount * saleCount * salePrice + amount;
        }

        $("#totalAmount").val(amount);

        var memberbalance = $("#memberbalance").val();

        if (memberbalance > amount) {
            $.messager.alert("温馨提示", "结算成功请提交")
        } else {
            $.messager.alert("温馨提示", "余额不足请充值");
        }
    })
})
//查询会员列表
function query() {
    var keyword = $("#keywords").textbox('getValue');
    $("#emp_datagrid").datagrid('load', {
        keyword: keyword,
    })
}

//提交明细
function submitSale() {

    var id = $("#emp_datagrid").datagrid("getSelected").id;

    var number = $("#order_product").datagrid("getSelected").point;
    //integral= 0-integral;

    var salePrice =$("#order_product").datagrid("getSelected").salePrice;
    var productName =$("#order_product").datagrid("getSelected").name;

    var salecount =$("#saleCount").val();

    var pid =$("#order_product").datagrid("getSelected").id;

    $.post("/member/integralUpdate",{id:id,number:number},function (data) {
        if (data.success) {
            $.messager.alert("温馨提示", '修改会员积分')
            $("#emp_datagrid").datagrid('load');

        } else {
            $.messager.alert("温馨提示", data.msg, 'warning')
        }
    });
    $.post("/member/memberBalanceUpdate",{id:id,salePrice:salePrice},function (data) {
        if (data.success) {
            $.messager.alert("温馨提示", '修改余额成功');
                $("#emp_datagrid").datagrid('load');
        } else {
            $.messager.alert("温馨提示", data.msg, 'warning')
        }
    });
  /*  $.post("/stock/productNumberSelect",{productName:productName},function (data) {
        if (data.success) {
           data =  eval(data);
            alert(data);
            $.messager.alert("温馨提示", '查询商品库存数量成功')
            alert(data.totalNumber);
            if (data.totalNumber<salecount){
                $.messager.alert("温馨提示", '库存数量不足或没有此商品了', 'warning')
                $("#order_product").datagrid('load');
            }else{


            }

        } else {
            $.messager.alert("温馨提示", data.msg, 'warning')
        }
    });*/
    $.post("/stock/productNumberUpdate",{productName:productName,salecount:salecount},function (data) {
        if (data.success) {
            $.messager.alert("温馨提示", '修改商品库存数量成功');
            $("#order_product").datagrid('load');
        } else {
            $.messager.alert("温馨提示", data.msg, 'warning')
        }
    });


    /* //$.post('/sale/save')
     var trArray = $("#edit_table_body tr");
     for (var i = 0; i < trArray.size(); i++) {
     var tr = $(trArray[i]);
     // 修改需要提交的表单的名称,加上新的索引值
     tr.find("[tag=product]").prop("name", "items[" + i + "].saleProductName");
     tr.find("[tag=srotName]").prop("name", "items[" + i + "].brand");
     tr.find("[tag=saleprice]").prop("name", "items[" + i + "].salePrice");
     tr.find("[tag=saleCount]").prop("name", "items[" + i + "].saleNumber");
     tr.find("[tag=AmountPrice]").prop("name", "items[" + i + "].saleAmount");
     }*/

    $("#sale_form").form("submit", {
        url: '/sale/save',
        success: function (data) {
            data = $.parseJSON(data);
            if (data.success) {
                $.messager.alert("温馨提示", '保存成功', function () {
                    window.location.reload();
                })
            } else {
                $.messager.alert("温馨提示", data.msg, 'warning')
            }
        }
    });




}
function queryProductForm() {

    var keywords = $("#keyword").textbox("getValue");
    alert(keywords)
    $("#order_product").datagrid('load', {
        keywords: keywords
    })
}
$(function () {
    $('#dd').dialog({
        title: '挂单系统',
        width: 1500,
        height: 1000,
        closed: true,
        cache: false,
        modal: true,
        buttons:"#bb"
    });


})
function regiseter() {
    $.messager.confirm('确认','您确认下面的操作吗？',function(r){
        if (r){
            $("#sale_form").form("submit", {
                url: '/sale/save',
                success: function (data) {
                    data = $.parseJSON(data);
                    if (data.success) {
                        $.messager.alert("温馨提示", '保存成功', function () {
                            window.location.reload();
                        })
                    } else {
                        $.messager.alert("温馨提示", data.msg, 'warning')
                    }
                }
            });
            $('#dd').dialog('open');
            var saleordernumber = $("#saleOrderNumber").val();
            var name = $("#product_name").val();
            var salecount = $("#saleCount").val();
            var totalamount = $("#totalAmount").val();
            var name = $("#product_name").val();


            $('#dg').datagrid({
                fit: true,
                rownumbers: true,

                data: [
                    {
                        saleordernumber: saleordernumber,
                        name: name,
                        salecount: salecount,
                        saleprice: $(salePrice).val(),
                        totalamount: totalamount
                    }

                ],
                fitColumns: true,
                columns: [[

                    {field: 'saleordernumber', title: '货号', width: 100},
                    {field: 'name', title: '商品', width: 100},
                    {field: 'salecount', title: '数量', width: 100},
                    {field: 'saleprice', title: '售价', width: 100},
                    {field: 'totalamount', title: '小计', width: 100}
                ]]

            });
            $("#sale_form").form("clear");
        }
    });
}
function cancel() {
    $("#dd").dialog("close");
}
function select() {
  var  row =  $('#dg').datagrid("getSelected");
  if(!row){
      $.messager.alert('提示信息',"请确定您要操作的那一行");
  }else{
      $.post("/sale/select",function (data) {
          $("#dd").dialog("close");
          if(data.success){
              $.messager.alert('提示信息',"取出订单成功");
          }else{
              $.messager.alert('提示信息',data.msg);
          }

      })
  }

}